package com.xzh.http;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * Created by 谢植会 on 2018/4/28.
 * 邮箱 ：347649749@qq.com
 * 版本 ： ver 1.0
 * 说明 ：
 */

public class ResponseInterceptorBody extends ResponseBody {

    private ResponseBody mResponseBody;
    private OkHttpInterceptorCallBack mCallBack;
    private BufferedSource mBufferedSource;

    public ResponseInterceptorBody(ResponseBody mResponseBody,OkHttpInterceptorCallBack mCallBack) {
        this.mResponseBody = mResponseBody;
        this.mCallBack = mCallBack;
    }

    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if(mBufferedSource == null)

            mBufferedSource = Okio.buffer(getsourse(mResponseBody.source()));

        return mBufferedSource;
    }

    private Source getsourse(Source source) {

        return new ForwardingSource(source) {
            int sum = 0;
            long totalSize = contentLength();
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {

                long len = super.read(sink, byteCount);
                sum += (len == -1 ? 0 : len);
                int progress = (int) ((sum * 1.0f / totalSize) * 100);
                LogUtils.log("ddfdf     progress :  "+progress);
                if (len != -1){
                    mCallBack.onProgress(progress);
                }else {
                    mCallBack.onFinish();
                }
                return len;
            }
        };
    }
}
